import { type ShcemeConfig, useFilterParams } from '@peng_kai/kit/admin/components/filter/src/useFilterParams';
import { getNextPageParam } from '~/modules/query-client';

/**
 * 函数用于创建一个带有过滤参数的无限滚动查询。
 *
 * @param apiFn - API函数
 * @param params - 过滤参数的配置
 * @returns 返回一个数组，包含查询对象和过滤参数
 */
export function useFilterInfiniteQuery<
  Api extends Api.Request,
  P extends Api.GetParam<Api>,
>(apiFn: Api, params: ShcemeConfig<P>) {
  const refetchTimes = ref(1);
  const queryParams = useFilterParams<Api.GetParam<Api>>(params);
  const query = useInfiniteQuery({
    queryKey: [apiFn.id, 'infinite', refetchTimes, queryParams.$params],
    queryFn: ctx => (apiFn({ ...queryParams.$params, ...ctx.pageParam }) as Promise<Api.GetData<Api>>),
    gcTime: 0,
    staleTime: 0,
    initialPageParam: { cursor: 0 },
    // placeholderData: keepPreviousData,
    getNextPageParam,
  });

  (query as any).refetchFromFirst = function () {
    refetchTimes.value++;
  };

  return [query, queryParams] as const;
}
